import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
const logout = async function() {
	await store.dispatch('user/logout')
	router.push(`/login`)
	window.location.reload()
	const loadingInstance = Loading.service({
		lock: true,
		text: 'Loading',
		spinner: 'el-icon-loading',
		background: 'rgba(0, 0, 0, 0.5)'
	})
	loadingInstance.close()
}
console.log(config)
const service = axios.create({
	// baseURL: process.env.VUE_APP_BASE_API, // url = base url + reques t url
	baseURL: window.config.getAuthUrl().baseUrl,
	// baseURL: '/mlsApi',
	withCredentials: false,
	timeout: 1000 * 60 * 15
})
// request interceptor
service.interceptors.request.use(
	config => {
		const token = getToken()
		if (config.mode === 'wx') {
			config.baseURL = window.config.getAuthUrl().wxBaseUrl
		}
		config.headers.Authorization = token ? ('Bearer ' + getToken()) : ''
		return config
	},
	error => {
		console.log(error) // for debug
		return Promise.reject(error)
	}
)
// response interceptor
service.interceptors.response.use(
	response => {
		const config = response.config
		const res = response.data
		// 如果是导出接口，直接返回数据
		if (config.type && config.type === 'export') {
			return res
		}
		if (res.type || config.type === 'important') {
			return res
		}
		if (res.code == 403) {
			MessageBox.alert('您的登录已过期，为了您的账户安全，请您重新登录后再操作', '登录过期', {
				confirmButtonText: '重新登录',
				showClose: false,
				callback: action => {
					logout()
				}
			})
			return
		} else if (res.code !== 1 && res.code !== 200) {
			Message({
				message: res.msg || 'Error',
				type: 'error',
				duration: 2 * 1000
			})
			return Promise.reject(new Error(res.msg || 'Error'))
		} else {
			return res
		}
	},
	error => {
		console.log('错误' + error) // for debug
		Message({
			message: error.msg || '网络错误，请稍后重试！',
			type: 'error',
			duration: 2 * 1000
		})
		return Promise.reject(error)
	}
)
export default service